package main

import (
	"context"
	"flag"
	"fmt"
	pb "gitee.com/go-programming-tour/gprc-demo/proto"
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
)

var port string

type GreeterServer struct {
	pb.UnimplementedGreeterServer
}

func (g *GreeterServer) SayHello(ctx context.Context, request *pb.HelloRequest) (*pb.HelloReplay, error) {
	return &pb.HelloReplay{
		Message: "hello world 这里是server端",
	}, nil
}

func (g *GreeterServer) SayList(request *pb.HelloRequest, stream grpc.ServerStreamingServer[pb.HelloReplay]) error {
	for i := 1; i <= 5; i++ {
		resp := &pb.HelloReplay{
			Message: fmt.Sprintf("你好 %s, 这是rpc服务端第 %d 条信息", request.Name, i),
		}
		if err := stream.Send(resp); err != nil {
			return err
		}
	}
	return nil
}

func (g *GreeterServer) SayRecord(stream grpc.ClientStreamingServer[pb.HelloRequest, pb.HelloReplay]) error {
	for {
		resp, err := stream.Recv()
		// 当读取完全部消息时，再回复
		if err == io.EOF {
			message := &pb.HelloReplay{Message: "say.record"}
			return stream.SendAndClose(message)
		}
		if err != nil {
			return err
		}
		log.Printf("SayRecord: %v", resp)
	}
	return nil
}

func (g *GreeterServer) SayRoute(stream grpc.BidiStreamingServer[pb.HelloRequest, pb.HelloReplay]) error {
	n := 0
	for {
		_ = stream.Send(&pb.HelloReplay{Message: "sayroute"})
		resp, err := stream.Recv()
		// 表示输入读完了
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		n++
		log.Printf("resp: %v", resp)
	}
	return nil
}

func init() {
	flag.StringVar(&port, "p", "8000", "启动端口")
	flag.Parse()
}

func main() {
	server := grpc.NewServer()
	pb.RegisterGreeterServer(server, &GreeterServer{})
	lis, _ := net.Listen("tcp", ":"+port)
	_ = server.Serve(lis)
}
